package com.tmsps.common.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.PropertyFilter;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.tmsps.common.annotation.JFilter;

import java.io.Serializable;
import java.util.*;

/**
 * @ClassName BeanJFilter
 * @description TODO
 * @author geek
 * @date 2020年07月01日 9:54
 */
@com.fasterxml.jackson.annotation.JsonFilter("BeanJFilter")
public class BeanJFilter extends SimpleBeanPropertyFilter implements Serializable {
    public Map<Class, Set<String>> includesClazz ;
    public BeanJFilter() {
        this.includesClazz = new HashMap<>();
    }
    public BeanJFilter addFilter(Class clazz, String propertyArray) {
        includesClazz.put(clazz, new HashSet<>(Arrays.asList(propertyArray.split(","))));
        return this;
    }
    @Override
    protected boolean include(BeanPropertyWriter writer) {
        if( includesClazz.containsKey(writer.getMember().getDeclaringClass()) ){
            return !this.includesClazz.get(writer.getMember().getDeclaringClass()).contains(writer.getName());
        }
        return true;
    }
    @Override
    protected boolean include(PropertyWriter writer) {
        if( includesClazz.containsKey(writer.getMember().getDeclaringClass()) ){
            return !this.includesClazz.get(writer.getMember().getDeclaringClass()).contains(writer.getName());
        }
        return true;
    }
    public static void setJFilter(JFilterValue jFilterValue, ObjectMapper objectMapper ){
        JFilter[] jFilter = jFilterValue.getJfilters();
        if (jFilter.length > 0) {
            BeanJFilter beanJFilter = new BeanJFilter();
            for (int i = 0; i < jFilter.length; i++) {
                beanJFilter.addFilter(jFilter[i].clazz(), "pk,tableName,"+jFilter[i].exclude());
                objectMapper.addMixIn(jFilter[i].clazz(), BeanJFilter.class);
            }
            SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
            FilterProvider filterProvider = serializationConfig.getFilterProvider();
            PropertyFilter nyfilter = filterProvider.findPropertyFilter("nyfilter", null);
         
            objectMapper.setFilterProvider(new SimpleFilterProvider()
                    .addFilter("BeanJFilter", beanJFilter)
                    .addFilter("nyfilter",nyfilter));
        }
    }
}
